﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SLLottery.LotterySrv;
using System.Net.NetworkInformation;
using SLLottery.Common;
namespace SLLottery
{
    public partial class App : Application
    {
        private static Dictionary<string, Object> m_Session = new Dictionary<string, object>();
        private static bool isHaveShow = false;
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
            InitializeComponent();
        }
        public static Dictionary<string, Object> Session
        {
            get
            {
                return App.m_Session;
            }
            set
            {
                App.m_Session = value;
            }
        }
        private Grid rootGrid = new Grid();
        public static void Navigation(UserControl newPage)
        {
            //获取当前的Appliaction实例 
            App currentApp = (App)Application.Current;
            //修改当前显示页面内容. 
            currentApp.rootGrid.Children.Clear();
            currentApp.rootGrid.Children.Add(newPage);
        }
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            NetworkChange.NetworkAddressChanged +=new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
            this.RootVisual = rootGrid;
            rootGrid.Children.Add(new LoginPage());
            //this.RootVisual = new  LoginPage();
        }
        //检查网络状态
        private bool isConnected = (NetworkInterface.GetIsNetworkAvailable());

        public bool IsConnected
        {
            get
            {
                return isConnected;
            }
        }
        void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            this.isConnected = (NetworkInterface.GetIsNetworkAvailable());
            if (!isConnected)
            {
                Navigation(new LoginPage());
                //MessageBox.Show("网络异常!");
            }
        }
        //private void DownloadAdditionalThings()
        //{
        //    WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);
        //    var client = new WebClient();
        //    client.UseDefaultCredentials = false;
        //    client.Credentials = new NetworkCredential("username", "password");
        //    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        //    client.DownloadStringAsync(new Uri("http://blog.gfader.com/"));
        //}

        private void Application_Exit(object sender, EventArgs e)
        {
            //LotterySrv.LotteryServiceClient _srv = WcfProxy.GetProxy;
            //if(App.Session.ContainsKey(Constant.USERNAME_SESSION)&&App.Session[Constant.USERNAME_SESSION]!=null)
            //    _srv.LoginOutAsync(App.Session[Constant.USERNAME_SESSION].ToString());
        }
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // 如果应用程序是在调试器外运行的，则使用浏览器的
            // 异常机制报告该异常。在 IE 上，将在状态栏中用一个 
            // 黄色警报图标来显示该异常，而 Firefox 则会显示一个脚本错误。
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // 注意: 这使应用程序可以在已引发异常但尚未处理该异常的情况下
                // 继续运行。 
                // 对于生产应用程序，此错误处理应替换为向网站报告错误
                // 并停止应用程序。
                e.Handled = true;
                if (MainPage.stkP != null)
                {
                    foreach (RadioButton rb in MainPage.stkP.Children)
                    {
                        rb.IsEnabled = true;
                    }
                }
                if (MainPage.stkR != null)
                {
                    foreach (RadioButton rb in MainPage.stkR.Children)
                    {
                        rb.IsEnabled = true;
                    }
                }
                if (!isHaveShow)
                {
                    //ChildWindow errorWin = new MessageWindow("您的网速不是很好或者服务器太过繁忙未能及时响应请求!");
                    ChildWindow errorWin = new MessageWindow(e.ExceptionObject.Message);
                    //errorWin.Show();
                    //errorWin.Closed += (s, er) =>
                    //{
                    //    if (errorWin.DialogResult == true)
                    //    {
                    //        isHaveShow = false;
                    //    }
                    //};
                  
                    isHaveShow = true;
                    Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
                }
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}
